package com.dgut.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dgut.entity.Products;
import com.dgut.entity.PurchaseOrder;
import com.dgut.mapper.ProductsMapper;
import com.dgut.mapper.PurchaseOrderMapper;
import com.dgut.result.PageResult;
import com.dgut.service.PurchaseOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;

@Service
@Slf4j
public class PurchaseOrderServiceImpl implements PurchaseOrderService {
    @Autowired
    private PurchaseOrderMapper purchaseOrderMapper;
    @Autowired
    private ProductsMapper productsMapper;

    /**
     * 生成进货单
     *
     * @param purchaseOrder
     */
    @Override
    @Transactional
    public void save(PurchaseOrder purchaseOrder) {
        purchaseOrder.setOrderDate(LocalDate.now());
        purchaseOrder.setPurchaseOrderStatus(0);//0未到货
        purchaseOrder.setExpectedDeliveryDate(LocalDate.now().plusDays(7));
        purchaseOrderMapper.insert(purchaseOrder);


        // 更新商品库存
        Products product = productsMapper.selectById(purchaseOrder.getProductId());
        product.setReorderCount(product.getReorderCount() + purchaseOrder.getQuantityOrdered());
        productsMapper.updateById(product);
    }

    /**
     * 分页查询
     *
     * @param currentPage
     * @param pageSize
     * @return
     */
    @Override
    public PageResult pageQuery(Integer currentPage, Integer pageSize) {
        Page<PurchaseOrder> page = new Page<>(currentPage, pageSize);
        Page<PurchaseOrder> page1 = purchaseOrderMapper.selectPage(page, null);
        return new PageResult(page1.getTotal(), page1.getRecords());
    }

    /**
     * 确认进货单完成
     *
     * @param id
     */
    @Override
    @Transactional
    public void confirm(Long id) {
        // 更新进货单状态
        PurchaseOrder purchaseOrder = purchaseOrderMapper.selectById(id);
        purchaseOrder.setPurchaseOrderStatus(1);
        purchaseOrderMapper.updateById(purchaseOrder);

        // 更新商品库存信息
        Products product = productsMapper.selectById(purchaseOrder.getProductId());
        product.setHandCount(product.getHandCount() + purchaseOrder.getQuantityOrdered());
        product.setReorderCount(product.getReorderCount() - purchaseOrder.getQuantityOrdered());
        productsMapper.updateById(product);
    }
}
